//
//  ViewController.m
//  TestZaker
//
//  Created by gang.xu on 13-4-25.
//  Copyright (c) 2013年 去哪儿. All rights reserved.
//

#import "ViewController.h"
#import "QNGridItem.h"

#define kQNGridItemUnvalidIndex     -1
#define kQNGridItemThreshold        30
#define kQNGridItemSize             100

@interface ViewController ()

@end

@implementation ViewController
@synthesize backgroundImage = _backgroundImage;
@synthesize scrollView = _scrollView;

- (void)viewDidLoad
{
    [super viewDidLoad];
    CGRect frame = self.view.frame;
    
    // backgroundImage
    _backgroundImage = [[UIImageView alloc] initWithFrame:CGRectMake(0, 0, 480, frame.size.height)];
    self.backgroundImage.image = [UIImage imageNamed:@"backgound.jpg"];
    [self.view addSubview:self.backgroundImage];
    
    // scrollView 
    _scrollView = [[UIScrollView alloc] initWithFrame:CGRectMake(0, 0, frame.size.width, frame.size.height)];
    self.scrollView.contentSize = CGSizeMake(frame.size.width, frame.size.height + 50);
    self.scrollView.showsVerticalScrollIndicator = NO;
    [self.view addSubview:self.scrollView];
    
    // TapGesture
    UITapGestureRecognizer *tapGesture = [[UITapGestureRecognizer alloc] initWithTarget:self action:@selector(handleTapGesture:)];
    [tapGesture setNumberOfTapsRequired:1];
    tapGesture.delegate = self;
    [self.scrollView addGestureRecognizer:tapGesture];
    
    // gridItems
    [self createItems];
}

- (void)didReceiveMemoryWarning
{
    [super didReceiveMemoryWarning];
}

- (void)dealloc
{
    [_backgroundImage release];
    [_scrollView release];
    [super dealloc];
}

- (void)createItems {
    // gridItems
    NSInteger index = 0;
    gridItems = [[NSMutableArray alloc] initWithCapacity:6];
    // 1
    QNGridItem *item = [QNGridItem allocWithFrame:CGRectMake(20, 20, kQNGridItemSize, kQNGridItemSize) delegate:self title:@"财经新闻" bgImage:[UIImage imageNamed:@"blueButton.jpg"]];
    item.isRemovable = YES;
    item.tag = index++;
    [gridItems addObject:item];
    [self.scrollView addSubview:item];
    [item release];
    // 2
    item = [QNGridItem allocWithFrame:CGRectMake(140, 20, kQNGridItemSize, kQNGridItemSize) delegate:self title:@"互联网新闻" bgImage:[UIImage imageNamed:@"blueButton.jpg"]];
    item.isRemovable = YES;
    item.tag = index++;
    [gridItems addObject:item];
    [self.scrollView addSubview:item];
    [item release];
    // 3
    item = [QNGridItem allocWithFrame:CGRectMake(20, 140, kQNGridItemSize, kQNGridItemSize) delegate:self title:@"体育新闻" bgImage:nil];
    item.tag = index++;
    [gridItems addObject:item];
    [self.scrollView addSubview:item];
    [item release];
    // 4
    item = [QNGridItem allocWithFrame:CGRectMake(140, 140, kQNGridItemSize, kQNGridItemSize) delegate:self title:@"娱乐八卦" bgImage:nil];
    item.tag = index++;
    [gridItems addObject:item];
    [self.scrollView addSubview:item];
    [item release];
    // 5
    item = [QNGridItem allocWithFrame:CGRectMake(20, 260, kQNGridItemSize, kQNGridItemSize) delegate:self title:@"军事频道" bgImage:nil];
    item.tag = index++;
    [gridItems addObject:item];
    [self.scrollView addSubview:item];
    [item release];
    // 6
    item = [QNGridItem allocWithFrame:CGRectMake(140, 260, kQNGridItemSize, kQNGridItemSize) delegate:self title:@"时尚频道" bgImage:nil];
    item.tag = index++;
    [gridItems addObject:item];
    [self.scrollView addSubview:item];
    [item release];
}

#pragma mark - Actions

// 点击空白处停止编辑状态
- (void)handleTapGesture:(UITapGestureRecognizer *)gestureRecognizer {
    if (isEditing) {
        for (QNGridItem *item in gridItems) {
            [item disableEditing];
        }
    }
    isEditing = NO;
}

#pragma mark - UIGestureRecognizerDelegate

// 设置点击手势只对scrollView有效
- (BOOL)gestureRecognizer:(UIGestureRecognizer *)gestureRecognizer shouldReceiveTouch:(UITouch *)touch {
    if(touch.view != self.scrollView) {
        return NO;
    }
    return YES;
}

#pragma mark-- QNGridItemDelegate

// 进入编辑状态
- (void)gridItemDidEnterEditingMode:(QNGridItem *)gridItem{
    for (QNGridItem *item in gridItems) {
        [item enableEditing];
    }
    isEditing = YES;
}

// 拖动控件
- (void)gridItemDidMoved:(QNGridItem *)gridItem withLocation:(CGPoint)point moveGestureRecognizer:(UILongPressGestureRecognizer *)recognizer{
    CGRect frame = gridItem.frame;
    CGPoint _point = [recognizer locationInView:self.scrollView];
    CGPoint pointInView = [recognizer locationInView:self.view];
    frame.origin.x = _point.x - point.x - 4;
    frame.origin.y = _point.y - point.y - 4;
    gridItem.frame = frame;
    
    NSInteger toIndex = [self indexOfLocation:_point];
    NSInteger fromIndex = gridItem.tag;
    
    if (toIndex != kQNGridItemUnvalidIndex && toIndex != fromIndex) {
        QNGridItem *moveItem = [gridItems objectAtIndex:toIndex];
        [self.scrollView sendSubviewToBack:moveItem];
        [UIView animateWithDuration:0.4 animations:^{
            CGPoint origin = [self orginPointOfIndex:fromIndex];
            //NSLog(@"origin:%f,%f",origin.x,origin.y);
            moveItem.frame = CGRectMake(origin.x, origin.y, moveItem.frame.size.width, moveItem.frame.size.height);
        }];
        [self exchangeItem:fromIndex withposition:toIndex];
        //移动
    }
#warning 下滑翻页未完成
}

// 结束拖动
- (void) gridItemDidEndMoved:(QNGridItem *)gridItem withLocation:(CGPoint)point moveGestureRecognizer:(UILongPressGestureRecognizer*)recognizer{
    CGPoint _point = [recognizer locationInView:self.scrollView];
    NSInteger toIndex = [self indexOfLocation:_point];
    if (toIndex == kQNGridItemUnvalidIndex) {
        toIndex = gridItem.tag;
    }
    CGPoint origin = [self orginPointOfIndex:toIndex];
    [UIView animateWithDuration:0.2 animations:^{
        gridItem.frame = CGRectMake(origin.x, origin.y, gridItem.frame.size.width, gridItem.frame.size.height);
    }];
}

#pragma mark-- private

#define rows 3
#define columns 2
#define itemsPerPage 6
#define space 20
#define gridHight 100
#define gridWith 100

- (NSInteger)indexOfLocation:(CGPoint)location{
    NSInteger index;
    NSInteger _page = location.x / 320;
    NSInteger row =  location.y / (gridHight + 20);
    NSInteger col = (location.x - _page * 320) / (gridWith + 20);
    if (row >= rows || col >= columns) {
        return kQNGridItemUnvalidIndex;
    }
    index = itemsPerPage * _page + row * 2 + col;
    if (index >= [gridItems count]) {
        return kQNGridItemUnvalidIndex;
    }
    
    return index;
}

- (CGPoint)orginPointOfIndex:(NSInteger)index{
    CGPoint point = CGPointZero;
    if (index > [gridItems count] || index < 0) {
        return point;
    }else{
        NSInteger _page = index / itemsPerPage;
        NSInteger row = (index - _page * itemsPerPage) / columns;
        NSInteger col = (index - _page * itemsPerPage) % columns;
        
        point.x = _page * 320 + col * gridWith + (col +1) * space;
        point.y = row * gridHight + (row + 1) * space;
        return  point;
    }
}

- (void)exchangeItem:(NSInteger)oldIndex withposition:(NSInteger)newIndex{
    ((QNGridItem *)[gridItems objectAtIndex:oldIndex]).tag = newIndex;
    ((QNGridItem *)[gridItems objectAtIndex:newIndex]).tag = oldIndex;
    [gridItems exchangeObjectAtIndex:oldIndex withObjectAtIndex:newIndex];
}

@end
